
var apiHost = wx.getStorageSync('apiHost');
var apiUpLoad = wx.getStorageSync('apiUpLoad');        //上传外网图片地址

Page({

  /**
   * 页面的初始数据
   */
  data: {
    uploadImg: [],              //上传照片
    images: [],                 //上传图片集合
    imageitemstring : [],       //拼接图片视频字符串
    locationInput: '添加定位',   //添加定位初始化值
    subHeight: false,           //下一步获取高度
    imageVieos : [],            //图片视频集合
    videoUrl : '',              //视频标签
    videoUrlDelFlag :'',        //删除视频的标识
    collageId:'',               //拼团id
    nextStepDetail:'',          //下一步详情
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var openId = wx.getStorageSync('openId');           //用户openId获取
    var collageId = wx.getStorageSync('collageId');     //拼团id
    var userId = wx.getStorageSync('userId');           //userid

    if (collageId!=''){
      //首次发布拼团详情
      that.nextStepDetail(collageId);
    }

    that.setData({
      openId: openId,
      userId: userId,
      collageId: collageId
    })
  },

  //计算底部按钮 距离上面的高度
  countDetailBtnCon: function () {
    var that = this;
    var images = that.data.images;

    if (images.length >= 3) {
      that.setData({
        subHeight: true
      })
    } else {
      that.setData({
        subHeight: false
      })
    }
  },
  /**
   * 上传图片
   */
  uploadImg: function () {

    var that = this;
    var images = that.data.images;
    var videoUrl = that.data.videoUrl;

    if (images.length >= 6) {
      wx.showModal({
        title: '提示',
        content: '最多只能添加6张图片',
        showCancel: false
      })
    } else if (images.length >= 6 && videoUrl!=''){
      wx.showModal({
        title: '提示',
        content: '最多上传一个视频',
        showCancel: false
      })
    }else {
      wx.showActionSheet({
        itemList: ['图片（至少一张）', '视频（最长30秒）'],
        success: function (res) {
          var typeFlag = '';
          //判断上传的是图片还是视频
          if (res.tapIndex == 0){
            typeFlag = 'image';
            that.uploadImages(typeFlag); //上传图片微信调起
          } else if (res.tapIndex == 1){
            typeFlag = 'video';
            that.uploadVideo(typeFlag); //上传视频微信调起
          }
        },
        fail: function (res) {
          wx.showToast({
            title: res.errMsg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
      })
    }
  },

  /**
   * 上传图片微信调起
   */
  uploadImages: function (typeFlag){
    var that = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        console.log(res)
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        var images = that.data.images;
        that.upload(that, tempFilePaths[0], typeFlag);
      }
    })
  },
  /**
   * 上传视频微信调起
   */
  uploadVideo: function (typeFlag){
    var that = this;
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 30,                  //最长时间30秒
      camera: 'back',
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePath = res.tempFilePath;
        that.upload(that, tempFilePath, typeFlag);
      }
    })
  },

  //商品图片传送到外网
  upload: function (page, path, typeFlag) {
    var that = this;
    wx.showToast({
      icon: "loading",
      title: "正在上传"
    }),

    wx.uploadFile({
      url: apiUpLoad + "image-server/uploadImage/oss",
      filePath: path,
      name: 'file',
      header: { "Content-Type": "multipart/form-data" },
      formData: {
        //和服务器约定的token, 一般也可以放在header中
        'session_token': wx.getStorageSync('session_token')
      },
      success: function (res) {
        var images = that.data.images;
        if (res.statusCode != 200) {
          wx.showModal({
            title: '提示',
            content: '上传失败',
            showCancel: false
          })
          return;
        }
        var data = res.data
        var aa = JSON.parse(data);  //字符串转json
        var imgUrl = aa.data.url;
        var imageitemstring = that.data.imageitemstring;

        // 判断是否是视频
        if ('video' == typeFlag){
          page.setData({ 
            videoUrl: imgUrl,
            videoUrlDelFlag: imageitemstring.length
          })
        }else{
          images.push(imgUrl);
        }
        //拼接images 和 video Json字符串
        
        var imageitem = '{ "type":"' + typeFlag + '","url":"' + imgUrl + '" }';
        imageitemstring.push(JSON.parse(imageitem));

        //上传成功
        page.setData({         
          imgUrl: imgUrl,
          imageVieos: imageitemstring,
          images: images,
          imageitemstring: imageitemstring
        })
        that.countDetailBtnCon();         //计算按钮居上高度
      },
      fail: function (e) {
          wx.showToast({
            title: e.errMsg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
      },
      complete: function () {
        wx.hideToast();  //隐藏Toast
      }
    })
  },
  //删除上传照片
  deleteImg: function (e) {
    var that = this;
    var images = that.data.images;
    var imageitemstring = that.data.imageitemstring;
    var index = e.currentTarget.dataset.index;
    
    // 删除方法
    images.splice(index, 1);
    imageitemstring.splice(index, 1);     

    // var imageList = '{ "imageVieos": [' + imageitemstring + ']}';     //重新获取值
    var imageList = imageitemstring      //重新获取值

    that.setData({
      images: images,
      imageitemstring: imageitemstring,
      imageVieos: imageList,
    });
    that.countDetailBtnCon();//计算按钮居上高度
  },

  /**
   *删除视频方法 
   */
  deleteVideo :function(){
    var that = this;
    var videoUrlDelFlag = that.data.videoUrlDelFlag;
    var imageitemstring = that.data.imageitemstring;
    imageitemstring.splice(videoUrlDelFlag, 1);

    // var imageList = '{ "imageVieos": [' + imageitemstring + ']}';     //重新获取值
    var imageList = imageitemstring     //重新获取值

    that.setData({
      imageitemstring: imageitemstring,
      imageVieos: imageList,
      videoUrl: ''
    })
  },
  /**
   * 获取定位
   */
  dingwei: function () {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        var name = res.name
        var address = res.address
        that.setData({
          locationInput: name
        })
      }
    })
  },

  /**
   * 获取描述详情
   */
  binddescriptBlur:function(e){
    this.setData({
      descript: e.detail.value
    }) 
  },

  /**
   * 跳转下一步 (表单提交)
   */
  firstCollageBox: function (e){
    var that = this;

    var userId = that.data.userId;                  //用户id

    var title = e.detail.value.title;               //标题
    var descript = that.data.descript;         //描述
    var localAddress = e.detail.value.localAddress; //地址
    var imageVieos = that.data.imageVieos;          //图片视频
    var collageId = that.data.collageId;            //图片视频

    var images = that.data.images;                  //图片集合 判断图片标识

    if (title==''){
      that.promptMsg("请填写标题");
      return;
    } else if (descript == ''){
      that.promptMsg("请输入描述信息");
      return;
    } else if (descript == '添加定位') {
      that.promptMsg("请选择定位");
      return;
    } else if (images.length==0){
      that.promptMsg("至少选择一张图片");
      return;
    }else{
      //下一步保存
      that.nextStep(userId, title, descript, localAddress, imageVieos, collageId);
    }
  },

  /**
   * 下一步保存
   */
  nextStep: function (userId, title, descript, localAddress, imageVieos, collageId){
    var that = this;
  
    wx.showLoading({
      title: '玩命加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "hpp/collage/nextStep",
      method:'POST',
      data: {
        collageId: collageId,
        userId: userId,
        title: title,
        descript: descript,
        localAddress: localAddress,
        imageVieos: imageVieos,
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;
        var collageId = res.data.data;//拼团Id

        if ("10000" == code){
          wx.setStorageSync('collageId', collageId);//拼团Id

          that.goNextSecond();//跳转下一步操作
        }else{
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        wx.hideLoading();   //隐藏加载loading
      },
      fail: function () {
        wx.hideLoading();   //隐藏加载loading
        wx.showToast({
          title: '网络异常',
          icon: 'none',
          duration: 2000,
          mask: true
        });
      }
    });
  },

  /**
   * 首次拼团详情
   */
  nextStepDetail: function (collageId){
    var that = this;

    wx.showLoading({
      title: '玩命加载中',
      icon: 'loading',
    });

    wx.request({
      url: apiHost + "hpp/collage/nextStepDetail",
      method: 'GET',
      data: {
        collageId: collageId
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        var code = res.data.code;
        var msg = res.data.msg;

        if ("10000" == code) {
          var nextStepDetail = res.data.data;  //第一步保存的详情
          var images = that.data.images;       //图片集合
          var videoUrl = that.data.videoUrl;   //视频

          var imageVideoVos = res.data.data.imageVideoVos;  //第一步保存的详情里面的图片视频

          // 初始化图片视频
          for (var i = 0;i<imageVideoVos.length;i++){
            var imgType = imageVideoVos[i].type;
            if (imgType =='image'){
              images.push(imageVideoVos[i].url);
            }
            if (imgType == 'video') {
              videoUrl = imageVideoVos[i].url;
            }

            that.setData({
              images:images,
              videoUrl: videoUrl
            });
          }
          that.setData({
            nextStepDetail: nextStepDetail,
            imageVieos: imageVideoVos,
            imageitemstring: imageVideoVos
          })
        } else {
          wx.showToast({
            title: msg,
            icon: 'none',
            duration: 2000,
            mask: true
          });
        }
        wx.hideLoading();   //隐藏加载loading
      },
      fail: function () {
        wx.hideLoading();   //隐藏加载loading
        wx.showToast({
          title: '网络异常',
          icon: 'none',
          duration: 2000,
          mask: true
        });
      }
    });
  },


  /**
   * 提示信息
   */
  promptMsg : function(msg){
      wx.showToast({
        title: msg,
        icon: 'none',
        duration: 2000,
        mask: true
      });
  },

  /**
   * 取消
   */
  cancel :function(){
    wx.showLoading({
      title: '跳转中',
      icon: 'loading',
      mask: true
    });
    wx.switchTab({
      url: '../../publishCollage/publishCollage',
      success: function () {
        wx.hideLoading();   //隐藏加载loading
      },
    });
  },

  /**
   * 跳转下一步操作
   */
  goNextSecond : function(){
    wx.showLoading({
      title: '跳转中',
      icon: 'loading',
      mask: true
    });
    wx.reLaunch({
      url: '../secondOrdinaryCollage/secondOrdinaryCollage',
      success: function () {
        wx.hideLoading();   //隐藏加载loading
      },
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})